package com.itluma.myshopping.servlet;

import com.itluma.myshopping.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 飞鸟
 * @create 2021-03-15 10:37
 * <p>
 * <p>
 * /模块名称？action=操作
 */
public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("action");//add/update/show/delete


        //如果知道自己有哪些方法可以调用
        Class<? extends BaseServlet> aClass = this.getClass();

        try {
            //1、通过反射获取需要执行的方法对象
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

            //2、执行方法
            Object result = method.invoke(this, req, resp);
            //4.集中处理返回值响应
            if (result != null) {
                //转发 重定向  返回字符
                String str = (String) result;
                if (str.startsWith(Constants.FORWARD)) {
                    //转发
                    String path = str.substring(str.indexOf(Constants.FLAG) + 1);
                    req.getRequestDispatcher(path).forward(req, resp);
                } else if (str.startsWith(Constants.REDIRECT)) {
                    //重定向
                    String path = str.substring(str.indexOf(Constants.INDEX) + 1);
                    resp.sendRedirect(path);
                } else {
                    resp.getWriter().println(str);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
